﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

namespace nr.Windows.Controls
{
    public partial class PrinterChoiceComboBox : UserControl
    {
        public delegate void SelectedPrinterChangedEventHandler(object sender, SelectedPrinterChangedEventArgs e);
        public class SelectedPrinterChangedEventArgs : EventArgs
        {
            public string PrinterName { get; private set; }

            public SelectedPrinterChangedEventArgs(string printerName)
                : base()
            {
                PrinterName = printerName;
            }
        }

        public event SelectedPrinterChangedEventHandler SelectedPrinterChanged;

        public string SelectedPrinter
        {
            get { return cbPrinters.SelectedIndex > -1 ? cbPrinters.SelectedItem.ToString() : "Nessuna stampante"; }
            set
            {
                if (cbPrinters.Items.Contains(value))
                    cbPrinters.SelectedIndex = cbPrinters.FindString(value);
            }
        }

        public PrinterChoiceComboBox()
        {
            InitializeComponent();
        }

        private void PrinterChoiceComboBox_Load(object sender, EventArgs e)
        {
            cbPrinters.Items.Clear();
            if (PrinterSettings.InstalledPrinters.Count > 0)
            {
                foreach (string printer in PrinterSettings.InstalledPrinters)
                    cbPrinters.Items.Add(printer);
                System.Drawing.Printing.PageSettings p = new PageSettings();
                SelectedPrinter = p.PrinterSettings.PrinterName;
            }
        }

        private void cbPrinters_SelectedIndexChanged(object sender, EventArgs e)
        {
            OnSelectedPrinterChanged(new SelectedPrinterChangedEventArgs(cbPrinters.SelectedText));
        }

        protected virtual void OnSelectedPrinterChanged(SelectedPrinterChangedEventArgs e)
        {
            if (SelectedPrinterChanged != null)
                SelectedPrinterChanged(this, e);
        }
    }
}
